<?php
declare(strict_types=1);

namespace SixShop\Lakala\Controller\Api;

use app\model\User;
use SixShop\Balpay\Entity\ExtensionBalpayLogEntity;
use SixShop\Balpay\Enum\BalpayLogTypeEnum;
use SixShop\Core\Request;
use SixShop\Lakala\Config;
use SixShop\Lakala\Entity\ProfitShareOrderEntity;
use think\Response;
use function SixShop\Core\page_response;
use function SixShop\Core\success_response;
use function SixShop\Core\throw_logic_exception;

class ProfitShareOrderController
{
    public function index(Request $request, ProfitShareOrderEntity $profitShareOrderEntity): Response
    {
        $params = [
            'user_id' => $request->userID,
        ];
        return page_response($profitShareOrderEntity->getOrderList($params, $request->pageAndLimit()));
    }

    public function save(
        Request $request,
        ProfitShareOrderEntity $profitShareOrderEntity,
        ExtensionBalpayLogEntity $extensionBalpayLogEntity,
        Config $config,
    ): Response
    {
        $userID = (int)$request->userID;
        $amount = $request->post('amount/f', 0);
        if ($amount < $config->profit_share_min) {
            throw_logic_exception('分账金额不能低于' . $config->profit_share_min);
        }
        if ($amount > $config->profit_share_max) {
            throw_logic_exception('分账金额不能高于' . $config->profit_share_max);
        }
        $balance = round((float)User::where('id', $userID)->value('balance'), 2);
        if ($balance < $amount) {
            throw_logic_exception('余额不足');
        }
        $receiverID = $request->post('receiver_id/d', 0);
        $result = $profitShareOrderEntity->transaction(function () use (
            $profitShareOrderEntity,
            $extensionBalpayLogEntity,
            $userID,
            $receiverID,
            $amount
        ){
            $profitShareOrder = $profitShareOrderEntity->createOrder($userID, $receiverID, $amount);
            $extensionBalpayLogEntity->change($userID, $amount, BalpayLogTypeEnum::PROFIT_SHARE, '分账', $profitShareOrder->id);

            return $profitShareOrder;
        });

        return success_response($result);
    }
}